package org.kjtc.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBException;

import org.kjtc.entity.SystemInfo;
import org.kjtc.util.Const;
import org.kjtc.util.FileUpload;
import org.kjtc.util.Tools;
import org.kjtc.util.XmlSerializer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class SystemInfoContorller extends BaseController {

	@ResponseBody
	@RequestMapping(value = "/saveSysInfo")
	public Object saveSysInfo(@RequestParam(value="systemName", required=false) String systemName,
			@RequestParam(value="systemLogo", required=false) MultipartFile file) throws JAXBException {

		ModelAndView mv = this.getModelAndView();
		String strXML = "";
		String filePath = Const.SYSTEMCONFIG_PATH_BUS;
		if (systemName != null && !systemName.isEmpty()) {
			SystemInfo.getInstance().setSystemName(systemName);
			XmlSerializer<SystemInfo> xSerializer = new XmlSerializer<SystemInfo>();
			strXML = xSerializer.marshallObj(SystemInfo.class, SystemInfo.getInstance(), "UTF-8");
			System.out.println(strXML);
			try {
				Tools.writeFile(filePath + Const.SYSNAMEINFO, strXML, true);
			} catch (IOException e) {
				e.printStackTrace();
				return "Error";
			}
		}
		if (file != null && !file.isEmpty()) {
			String fileName = null;
			try {
				fileName = FileUpload.upload(file, filePath, Const.SYSLOGO, Const.IMG_SUFFIX);
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("上传图片" + file.getOriginalFilename() + "已成功上传到" + filePath + fileName);
		}

		mv.setViewName("systemManage/systemInfo");
		return mv;
	}
	@ResponseBody
	@RequestMapping(value = "/searchSysInfo")
	public Object searchSysInfo() throws JAXBException, FileNotFoundException {

		Map<String, Object> map = new HashMap<String, Object>();
		String filePath = Const.SYSTEMCONFIG_PATH_BUS;
		File file = new File(filePath + Const.SYSNAMEINFO);
		String systemName = Const.SYSNAMENAME_BUS;
		if (file.exists()) {
			XmlSerializer<SystemInfo> xSerializer = new XmlSerializer<SystemInfo>();
			systemName = xSerializer.unMarshallXml(file, SystemInfo.class).getSystemName();
		}
		map.put("systemName", systemName);

		File fileImg = new File(filePath + Const.SYSLOGO + Const.IMG_SUFFIX);
		if (fileImg.isFile() && fileImg.exists()) {
			try {
				map.put("systemLogo", Tools.readLocalImageToBase64(fileImg));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return map;
	}
}
